﻿using DDD.Core.CQRS;
using DDD.Core.Result;
using DDD.Domain.Abstract.UnitOfWork;
using DDD.Domain.Repositories;

namespace DDD.Application.Commands.UserCommand.UpdateUserById
{
    internal class UpdateUserByIdCommandHandler : ICommandHandler<UpdateUserByIdCommand, ApiResult<bool>, bool>
    {
        private readonly IUserRepository _userRepository;
        private readonly IUnitOfWork _unitOfWork;

        public UpdateUserByIdCommandHandler(IUserRepository userRepository, IUnitOfWork unitOfWork)
        {
            _userRepository = userRepository;
            _unitOfWork = unitOfWork;
        }

        public async Task<ApiResult<bool>> Handle(UpdateUserByIdCommand request, CancellationToken cancellationToken)
        {
            var dbUser = _userRepository.Get(request.Id);

            dbUser.SetUserName(request.UserName)
                .SetPhone(request.Phone)
                .SetEmail(request.Email)
                .SetPassword(request.Password)
                .SetSex(request.Sex)
                .SetAddress(request.Address);

            _userRepository.Update(dbUser);

            var result = await _unitOfWork.SaveChanegeAsync() > 0;

            return ApiResult<bool>.Success(result);
        }
    }
}
